<!-- src/components/TemplateView.vue -->
<template>
  <v-app>
    <v-container>
      <v-row>
        <v-col cols="12">
          <v-card>
  <v-card-title>
    用户管理
    <v-spacer></v-spacer>
    <v-btn color="primary" @click="openDialog()">
      添加用户
    </v-btn>
  </v-card-title>
  <v-card-text>
    <v-text-field
      v-model="search"
      label="搜索用户"
      class="mb-4"
      clearable
    ></v-text-field>
    <v-data-table
      :headers="headers"
      :items="users"
      :loading="loading"
      :search="search"
      class="elevation-1"
    >
      <template v-slot:item.actions="{ item }">
        <v-icon small @click="deleteItem(item)" class="mr-4">
          mdi-delete
        </v-icon>
        <v-icon small @click="openEditDialog(item)">
          mdi-pencil
        </v-icon>
      </template>
    </v-data-table>
  </v-card-text>
</v-card>
        </v-col>
      </v-row>

      <!-- 编辑对话框 -->
      <v-dialog v-model="dialog" max-width="500px">
        <v-card>
          <v-card-title>
            <span>{{ formTitle }}</span>
          </v-card-title>
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12">
                  <v-text-field
                    v-model="editedItem.name"
                    label="用户名"
                  ></v-text-field>
                </v-col>
                <v-col cols="12">
                  <v-text-field
                    v-model="editedItem.pass"
                    label="密码"
                  ></v-text-field>
                </v-col>
                <v-col cols="12">
                  <v-text-field
                    v-model="editedItem.times"
                    label="使用次数"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-container>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="close">取消</v-btn>
            <v-btn color="blue darken-1" text @click="save">保存</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

      <!-- 删除确认对话框 -->
      <v-dialog v-model="dialogDelete" max-width="500px">
        <v-card>
          <v-card-title>确认删除</v-card-title>
          <v-card-text>确定要删除用户吗？</v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="closeDelete">取消</v-btn>
            <v-btn color="blue darken-1" text @click="deleteItemConfirm">确认</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-container>
  </v-app>
</template>

<script>

const API_BASE = import.meta.env.VITE_API_BASE || 'http://106.75.215.61:3000';

export default {
  name: 'UserView',
  data: () => ({
    apiBase: API_BASE,
    dialog: false,
    dialogDelete: false,
    loading: false,
    search: '', // 搜索关键词
    // ✅ 改为 Vuetify 3 的写法：title + key
    headers: [
      { title: '用户ID', key: 'id' },
      { title: '用户名', key: 'name' },
      { title: '密码', key: 'pass' },
      { title: '使用次数', key: 'times' },
      { title: '操作', key: 'actions', sortable: false }
    ],
    users: [],
    editedIndex: -1,
    editedItem: {
      id: '',
      name: '',
      pass: '',
      times: ''
    },
    defaultItem: {
      id: '',
      name: '',
      pass: '',
      times: ''
    }
  }),

  computed: {
    formTitle() {
      return this.editedIndex === -1 ? '新增用户' : '编辑用户'
    },
  },

  methods: {
    async getAllUsers() {
      this.loading = true
      try {
        console.log(this.apiBase)
        const res = await this.$axios.get(`${this.apiBase}/getAllUsers`)
        this.users = res.data
      } catch (e) {
        this.$toast?.error('获取用户列表失败')
      } finally {
        this.loading = false
      }
    },

    async deleteUser(id) {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/deleteUser/` + id)
        if (res.status === 200) {
          this.$toast?.success('删除成功')
        } else {
          throw new Error('删除失败')
        }
      } catch (e) {
        this.$toast?.error('删除失败')
      } finally {
        this.loading = false
      }
    },

    openDialog() {
      this.editedIndex = -1
      this.editedItem = Object.assign({}, this.defaultItem)
      this.dialog = true
    },

    openEditDialog(item) {
      this.editedIndex = this.users.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.dialog = true
    },

    deleteItem(item) {
      this.editedIndex = this.users.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.dialogDelete = true
    },

    close() {
      this.dialog = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    closeDelete() {
      this.dialogDelete = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    async save() {
      if (!this.editedItem.name || !this.editedItem.pass) {
        this.$toast?.error('用户名和密码不能为空')
        return
      }

      // times 必须是数字
      const timesNum = Number(this.editedItem.times)
      if (isNaN(timesNum) || timesNum < 0) {
        this.$toast?.error('使用次数必须是非负数字')
        return
      }
      this.editedItem.times = timesNum

      if (this.editedIndex > -1) {
        this.loading = true
        try {
          const response = await this.$axios.post(`${this.apiBase}/updateUser`, {
            id: this.editedItem.id,
            name: this.editedItem.name,
            pass: this.editedItem.pass,
            times: this.editedItem.times
          })

          if (response.status !== 200) throw new Error('更新失败')

          this.$toast?.success('更新成功')

          Object.assign(this.users[this.editedIndex], this.editedItem)
          this.close()
        } catch (e) {
          this.$toast?.error('上传失败')
        } finally {
          this.loading = false
        }
      } else {
        this.loading = true
        try {
          const response = await this.$axios.post(`${this.apiBase}/addUser`, {
            name: this.editedItem.name,
            pass: this.editedItem.pass,
            times: this.editedItem.times
          })

          if (response.status !== 200) throw new Error('创建失败')

          const { id, name, pass, times } = response.data.data
          Object.assign(this.editedItem, { id, name, pass, times })
          this.$toast?.success('创建成功')

          this.users.push(this.editedItem)
          this.close()
        } catch (e) {
          this.$toast?.error('创建失败')
        } finally {
          this.loading = false
        }
      }

      this.close()
    },

    async deleteItemConfirm() {
      await this.deleteUser(this.editedItem.id)
      this.users.splice(this.editedIndex, 1)
      this.closeDelete()
    }
  },

  mounted() {
    this.getAllUsers()
  }
}
</script>
